package priv.pfz.basedao.mybatis.sqlprovider;

import org.apache.ibatis.builder.annotation.ProviderContext;
import priv.pfz.basedao.Utils;
import priv.pfz.basedao.info.FieldInfo;
import priv.pfz.basedao.info.DaoInfo;
import priv.pfz.basedao.mybatis.DaoInfoCache;
import priv.pfz.basedao.sharding.ShardingInfo;
import priv.pfz.basedao.sharding.ShardingManager;
import priv.pfz.basedao.sqlbuilder.SQL;

import java.util.Map;

/**
 * DELETE FROM table WHERE a=example.a AND b=example.b
 * logic delete: UPDATE table SET delete_flag = id WHERE a=example.a AND b=example.b AND delete_flag=0
 * @author yyjxp
 * 2024/1/28 23:55
 */
public class DeleteByExampleSqlProvider extends BaseSqlProvider {

    public String provideSql(Object example, ProviderContext context) {
        return innerProvideSql(example, null, null, context);
    }

    public String provideShardingSql(Object example, ShardingInfo shardingInfo, ProviderContext context) {
        return innerProvideSql(example, "arg0", shardingInfo, context);
    }

    private String innerProvideSql(Object example, String entityArgName, ShardingInfo shardingInfo, ProviderContext context) {
        Utils.checkNotNull(example, "example不能为空");
        DaoInfo daoInfo = DaoInfoCache.getDaoInfo(context.getMapperType());
        Map<String, Object> valueMap = getValueMap(daoInfo, example);
        Utils.checkNotEmpty(valueMap, "example字段不能全部为空");
        ShardingManager shardingManager = new ShardingManager(daoInfo, shardingInfo);

        SQL sql = new SQL();
        for (FieldInfo fieldInfo : daoInfo.getFieldInfos()) {
            if (!valueMap.containsKey(fieldInfo.getFieldName())) {
                continue;
            }
            sql.WHERE(getFieldEquals(entityArgName, fieldInfo));
            shardingManager.addShardingInfo(fieldInfo, valueMap.get(fieldInfo.getFieldName()));
        }
        if (daoInfo.isEnableLogicDelete()) {
            sql.WHERE(getLogicDeleteWhere(daoInfo));
            sql.UPDATE(shardingManager.getShardingTable());
            sql.SET(getLogicDeleteSet(daoInfo));
        } else {
            sql.DELETE_FROM(shardingManager.getShardingTable());
        }
        String sqlStr = sql.toString();
        sqlStr += shardingManager.getThirdShardingStr();
        System.out.println(sqlStr);
        return sqlStr;
    }
}
